'use strict';

const Service = require('egg').Service;
const {
  md5
} = require('utility');
const jwt = require('jsonwebtoken');

class UserService extends Service {
    async login() {
        const {
          ctx,
          app
        } = this;
        // 解构出用户民和密码
        const {
          username,
          password
        } = ctx.request.body;
        console.log('执行');
        // 根据用户名和密码在数据库中查找对应的用户
        const userInfo = await app.mysql.get('users', {
          username,
          password: md5(JSON.stringify(password))
        });
        if (userInfo) {
          const token = jwt.sign({
            ...userInfo
          }, app.keys[0]);
          return {
            data: userInfo,
            token
          }
        } else {
          return "账户或密码错误"
        }
    
      }
      async register() {
        const {
          ctx,
          app
        } = this;
        const {
          username,
          password
        } = ctx.request.body;
        // 查找当前用户名是否已经被注册
        const userInfo = await app.mysql.get('users', {
          username,
        });
        if (userInfo) {
          return '当前用户名已经被注册'
        } else {
          // 插入数据
          const res = await app.mysql.insert('users', {
            username,
            password: md5(JSON.stringify(password)),
            role: "管理员",
          });
    
          return res
        }
      }
}

module.exports = UserService;
